<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>节点配置</title>
    <style>
.json-container {
      padding: 15px;
      background: #f8f8f8;
      border-radius: 5px;
      max-height: 70vh;
      overflow: auto;
      font-family: Consolas, Monaco, monospace;
      line-height: 1.2;
    }
    .json-key {
      color: #92278f;
      font-weight: bold;
    }
    .json-string {
      color: #3ab54a;
      white-space: pre-wrap;
      word-break: break-word;
      word-wrap: break-word;
    }
    .json-number { color: #25aae2; }
    .json-boolean { color: #f98280; }
    .json-null { color: #f1592a; }
    .json-collapse {
      cursor: pointer;
      display: inline-block;
      width: 16px;
      text-align: center;
    }
    .json-line {
      display: block;
      min-height: 20px;
    }
    .json-hidden { display: none; }
        .popup-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .popup-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 500px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="url"] {
            width: 70%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .radio-group {
            display: flex;
            gap: 15px;
            margin: 10px 0;
        }
        .hidden {
            display: none;
        }
        .btn-submit {
            background: #1890ff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="popup-overlay">
    <div class="popup-content">
        <h2>编辑节点</h2>
        <form id="nodeForm" action="edit_node_api" method="POST">
            {% if node_type == 0%}
                <!--动态规则表单-->
                <div id="dynamic-form" class="tab-content">
                    <input type="text" name="id" value="{{id}}" style="display: none;">
                    <input type="text" name="node_type" value=0 style="display: none;">
                    <div class="form-group">
                        <label for="column_name">节点名称:</label>
                        <input type="text" name="column_name" value="{{column_name}}">
                    </div>
                    <div class="form-group">
                        <label for="column_url">节点URL:</label>
                        <input type="url" name="column_url" value="{{column_url}}">
                    </div>
                    <div class="form-group">
                        <label>节点规则类型:</label>
                        <div class="radio-group">
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=0 {% if column_rule_type is 0%}checked{%endif%}>XPATH</label>
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=1 {% if column_rule_type is 1%}checked{%endif%}>正则</label>
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=2 {% if column_rule_type is 2%}checked{%endif%}>JSON</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="column_rule">节点规则内容:</label>
                        <input type="text" name="column_rule" value="{{column_rule}}">
                    </div>
                    <div class="form-group">
                        <label for="column_prefix">节点链接前缀:</label>
                        <input type="text" name="column_prefix" value="{{column_prefix}}">
                    </div>
                    <div class="form-group">
                        <label for="page_rule">分页规则:</label>
                        <input type="text" name="page_rule" value="{{page_rule}}">
                    </div>
                    <div class="form-group">
                        <label for="list_rule_type">列表规则类型:</label>
                        <div class="radio-group">
                           <label typeof="radio"><input type="radio" name="list_rule_type" value=0 {% if list_rule_type is 0%}checked{%endif%}>XPATH</label>
                            <label typeof="radio"><input type="radio" name="list_rule_type" value=1 {% if list_rule_type is 1%}checked{%endif%}>正则</label>
                            <label typeof="radio"><input type="radio" name="list_rule_type" value=2 {% if list_rule_type is 2%}checked{%endif%}>JSON</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="list_rule">列表规则内容:</label>
                        <input type="text" name="list_rule" value="{{list_rule}}">
                    </div>
                    <div class="form-group">
                        <label for="list_prefix">详情链接前缀:</label>
                        <input type="text" name="list_prefix" value="{{list_prefix}}">
                    </div>
                   <div class="form-group">
                        <label for="detail_url_rule">原详情链接</label>
                        <input type="text" name="detail_url_rule" placeholder="详情为json时使用"  value="{{detail_url_rule}}">
                    </div>
                </div>
            {% elif node_type == 1%}
                <!--静态规则表单-->
                <div id="static-form" class="tab-content" style="padding-top: 10px">
                    <input type="text" name="id" value="{{id}}" style="display: none;">
                    <input type="text" name="website_id" value="{{website_id}}" style="display: none;">
                    <input type="text" name="node_type" value=1 style="display: none;">
                    <div class="form-group">
                        <label for="column_name">节点名称:</label>
                        <input type="text" name="column_name" value="{{column_name}}">
                    </div>
                    <div class="form-group">
                        <label for="column_url">节点URL:</label>
                        <input type="url" name="column_url"  value="{{column_url}}">
                    </div>
                    <div class="form-group">
                        <label>节点规则类型:</label>
                        <div class="radio-group">
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=0 {% if column_rule_type is 0%}checked{%endif%}>XPATH</label>
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=1 {% if column_rule_type is 1%}checked{%endif%}>正则</label>
                            <label typeof="radio"><input type="radio" name="column_rule_type" value=2 {% if column_rule_type is 2%}checked{%endif%}>JSON</label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="column_rule">节点规则内容:</label>
                        <input type="text" name="column_rule" value="{{column_rule}}">
                    </div>
                    <div class="form-group">
                        <label for="column_prefix">节点链接前缀:</label>
                        <input type="text" name="column_prefix" value="{{column_prefix}}">
                    </div>
                    <div class="form-group">
                        <label for="page_rule">分页规则:</label>
                        <input type="text" name="page_rule" value="{{page_rule}}">
                    </div>

                    <div class="form-group">
                        <label for="city">城市:</label>
                        <input type="text" name="city"  value="{{city}}">
                    </div>
                    <div class="form-group">
                        <label for="gender">性别:</label>
                        <input type="text" name="gender" value="{{gender}}">
                    </div>
                    <div class="form-group">
                        <label for="season">季度:</label>
                        <input type="text" name="season" value="{{season}}">
                    </div>
                    <div class="flex justify-end pt-4" style="padding-top: 60px;">
                        <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">保存</button>
                        <button type="button" onclick="Check(this)" value=1 class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">校验</button>
                        <button type="button" id="cancelBtn" class="px-4 py-2 border rounded mr-3 hover:bg-gray-100">取消</button>
                    </div>
                </div>

            {% elif node_type == 2%}
            <!--详情规则表单-->
                <div id="detail-form" class="tab-content" style="padding-top: 10px;">
                    <input type="text" name="id" value="{{id}}" style="display: none;">
                    <input type="text" name="website_id" value="{{website_id}}" style="display: none;">
                    <input type="text" name="node_type" value=2 style="display: none;">
                    <div class="form-group">
                        <label for="column_name">详情链接:</label>
                        <input type="text" name="detail_url" value="{{column_url}}">
                    </div>

                    <table class="rule-table">
                        <thead>
                        <tr>
                            <th width="5%">激活</th>
                            <th width="13%">字段</th>
                            <th width="28%">规则类型</th>
                            <th>规则内容</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for config in column_rule %}
                            {% if config.field != 'source_url'%}
                                <tr>
                                    <td>
                                        <input type="checkbox" class="toggle-btn" {% if config.select != 'off' %}checked{%endif%}>
                                    </td>
                                    <td data-model-name="filed" data-value="{{ config.field }}">{{ config.name}}</td>
                                    <td>
                                        <label>
                                            <input type="radio" name="{{config.field}}_rule_type" value=0 {% if config.rule_type == 0%}checked{%endif%}>
                                            <span>XPATH</span>
                                        </label>
                                        <label>
                                            <input type="radio" name="{{config.field}}_rule_type" value=1 {% if config.rule_type == 1%}checked{%endif%}>
                                            <span>REG</span>
                                        </label>
                                        <label>
                                            <input type="radio" name="{{config.field}}_rule_type" value=2 {% if config.rule_type == 2%}checked{%endif%}>
                                            <span>JSON</span>
                                        </label>
                                    </td>
                                    <td><input type="text" class="rule-input" value="{{config.value}}"></td>
                                </tr>
                            {% else %}
                                <tr>
                                    <td>
                                        <input type="checkbox" class="toggle-btn" {% if config.select != 'off' %}checked{%endif%}>
                                    </td>
                                    <td data-model-name="filed" data-value="{{config.field}}">{{config.name}}</td>
                                    <td></td>
                                    <td><input type="text" class="rule-input" placeholder="响应为json时使用" value="{{config.value}}"></td>
                                </tr>
                            {%endif%}
                        {% endfor %}
                    </tbody>
                </table>
                <div class="flex justify-end pt-4" style="padding-top: 6px;">
                    <button type="button" id="submitBtn" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">保存</button>
                    <button type="button" onclick="Check(this)" value=2 class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">校验</button>
                    <button type="button" id="cancelBtn" class="px-4 py-2 border rounded mr-3 hover:bg-gray-100">取消</button>
                </div>
            </div>
            {% endif %}

        </form>
    </div>
</div>
<script src="https://unpkg.com/layui@2.6.8/dist/layui.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>

function formatJson(json) {
    if (typeof json !== 'string') {
        json = JSON.stringify(json, null, 2);
    }
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
    function(match) {
        var cls = 'json-number';
        if (/^"/.test(match)) {
            cls = /:$/.test(match) ? 'json-key' : 'json-string';
        } else if (/true|false/.test(match)) {
            cls = 'json-boolean';
        } else if (/null/.test(match)) {
            cls = 'json-null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}
const cancelBtn = document.getElementById('cancelBtn');
cancelBtn.addEventListener('click', () => {
    history.back();
});
{% if node_type == 1 %}
    document.getElementById('static-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = new FormData(e.target);
      console.log(formData)
      try {
        const response = await fetch(e.target.action, {
          method: 'POST',
          body: formData
        });
        const result = await response.json(); // 解析JSON返回值
        if (result.code == 200){
            alert(result.message);
            window.location.href="node_list?website_id={{website_id}}"
        }else{
            alert('提交失败:' + result.data);
        }
      } catch (error) {
        console.error('提交失败:', error);
      }
    });
 {% endif %}

function Check(e){
    const node_type = $(e).val();
    console.log(node_type);
    var formValues = {};
    if (node_type == 1){
        const formElements = document.querySelectorAll('#static-form input');
        formElements.forEach(element => {
            if (element.type === 'radio') {
                if (element.checked) {
                    formValues[element.name] = element.value;
                }
            } else {
                formValues[element.name] = element.value;
            }
        });
        }else if (node_type == 2){
            const rows = document.getElementById('detail-form').querySelectorAll('tbody tr');
            const result = [];
            rows.forEach(row => {
                var rowData;
                const label_name = row.querySelector('[data-model-name="filed"]').getAttribute('data-value')
                if (label_name != 'source_url'){
                    rowData ={
                        checked: row.querySelector('.toggle-btn').checked ? 'on' : 'off',
                        rule_type: row.querySelector('input[type="radio"]:checked').value,
                        value: row.querySelector('[class="rule-input"]').value
                    };
                }else{
                    rowData ={
                        checked: row.querySelector('.toggle-btn').checked ? 'on' : 'off',
                        rule_type: '',
                        value: row.querySelector('[class="rule-input"]').value
                    };
                }
                const labelData = {[label_name]: rowData}
                result.push(labelData);
            });

            formValues = {
                detail_url: document.querySelector('#detail-form input[name="detail_url"]').value,
                website_id: document.querySelector('#detail-form input[name="website_id"]').value,
                node_type: document.querySelector('#detail-form input[name="node_type"]').value,
                column_rule: result
            }
        }
        var loadingIndex = layer.msg('正在加载数据...', {
            icon: 16,
            shade: 0.01,
            time: 0
        });
        $.ajax({
            url: '/website/check_rule',
            type: 'GET',
            data: formValues,
            success: function(response) {
                layer.close(loadingIndex);

                // 格式化JSON数据
                var formattedJson = formatJson(response.data);

                // 弹出包含格式化JSON的弹窗
                layer.open({
                  type: 1,
                  title: 'JSON数据查看器',
                  area: ['800px', '600px'],
                  shadeClose: true,
                  content: '<div class="json-container"><pre>' + formattedJson + '</pre></div>',
                  btn: ['关闭'],
                  success: function(layero, index){
                    // 添加折叠功能
                    var pre = layero.find('pre');
                    pre.on('click', function(e){
                      if (e.target.tagName === 'SPAN' && e.target.classList.contains('json-key')) {
                        var next = e.target.nextSibling;
                        if (next && next.nodeType === 3 && next.nodeValue.trim() === ':') {
                          var parent = e.target.parentNode;
                          if (parent.nextSibling && parent.nextSibling.nodeType === 1) {
                            var target = parent.nextSibling;
                            target.style.display = target.style.display === 'none' ? '' : 'none';
                          }
                        }
                      }
                    });
                  }
                });
            },
            error: function(xhr) {
                layer.close(loadingIndex);
                layer.alert('请求失败，请重试', {icon: 2});
            }
        });
    }

    $('#submitBtn').click(function() {
        const rows = document.getElementById('detail-form').querySelectorAll('tbody tr');
        const result = [];
        rows.forEach(row => {
            var rowData;
            const label_name = row.querySelector('[data-model-name="filed"]').getAttribute('data-value')
            console.log(name)
            if (label_name != 'source_url'){
                rowData ={
                    checked: row.querySelector('.toggle-btn').checked ? 'on' : 'off',
                    rule_type: row.querySelector('input[type="radio"]:checked').value,
                    value: row.querySelector('[class="rule-input"]').value
                };
            }else{
                rowData ={
                    checked: row.querySelector('.toggle-btn').checked ? 'on' : 'off',
                    rule_type: '',
                    value: row.querySelector('[class="rule-input"]').value
                };
            }
            const labelData = {[label_name]: rowData}
            result.push(labelData);
        });
        console.log(result)

        const params = {
            detail_url: document.querySelector('#detail-form input[name="detail_url"]').value,
            website_id: document.querySelector('#detail-form input[name="website_id"]').value,
            node_type: document.querySelector('#detail-form input[name="node_type"]').value,
            column_rule: result
        }
        $.ajax({
            url: '/website/create_node',
            type: 'POST',
            data: params,
            success: function(response) {
                alert(response.message);
                location.reload()
            },
            error: function(xhr) {
                $('#responseOutput').text('错误: ' + xhr.status + ' ' + xhr.statusText);
                $('#responseContainer').removeClass('hidden');
            }
        });
    });

</script>
</body>
</html>
